<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * 采用最新Thinkphp5助手函数特性实现单字母函数M D U等简写方式
 * ============================================================================
 * Author: 当燃
 * Date: 2015-09-09
 */

namespace app\admin\controller;

use think\AjaxPage;
use think\Page;
use think\Model;
use think\Db;
use think\Loader;

class Married extends Base
{

    public function character_index()
    {
        $where = "";
        $keyword = I('keyword');
        $where = $keyword ? " name like '%$keyword%' " : "";
        $count = Db::name("user_character")->where($where)->count();
        $Page = $pager = new Page($count, 10);
        $characterList = Db::name("user_character")->where($where)->order("sort")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        //        $cat_list = M('goods_category')->where("parent_id = 0")->getField('id,name'); // 已经改成联动菜单
        //        $this->assign('cat_list',$cat_list);
        $this->assign('pager', $pager);
        $this->assign('show', $show);
        $this->assign('characterList', $characterList);
        return $this->fetch('characterList');
    }

    /**
     * 添加修改编辑  性格特点
     */
    public function addEditCharacter()
    {
        $id = I('id');
        if (IS_POST) {
            $data = I('post.');
            //            $characterValidate = Loader::validate('Character');
            //            if(!$characterValidate->batch()->check($data)){
            //                $return = ['status'=>0,'msg'=>'操作失败','result'=>$characterValidate->getError()];
            //                $this->ajaxReturn($return);
            //            }
            if ($id) {
                Db::name("user_character")->update($data);
            } else {
                Db::name("user_character")->insert($data);
            }
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'result' => '']);
        }
        $cat_list = M('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
        $this->assign('cat_list', $cat_list);
        $character = M("user_character")->find($id);
        $this->assign('character', $character);
        return $this->fetch('_character');
    }

    /**
     * 删除性格特点
     */
    public function delCharacter()
    {
        $ids = I('post.ids', '');
        empty($ids) && $this->ajaxReturn(['status' => -1, 'msg' => '非法操作！']);
        $character_ids = rtrim($ids, ",");
        $res = Db::name('user_character')->whereIn('id', $character_ids)->delete();
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'url' => U("Admin/married/character_index")]);
        }
        $this->ajaxReturn(['status' => -1, 'msg' => '操作失败', 'data' => '']);
    }

    // 级别列表
    public function customer_index()
    {
        $where = "";
        $keyword = I('keyword');
        $where = $keyword ? " name like '%$keyword%' " : "";
        $count = Db::name("user_level")->where($where)->count();
        $Page = $pager = new Page($count, 10);
        $levelList = Db::name("married_user_level")->where($where)->order("sort")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $cat_list = M('goods_category')->where("parent_id = 0")->getField('id,name'); // 已经改成联动菜单
        $this->assign('cat_list', $cat_list);
        $this->assign('pager', $pager);
        $this->assign('show', $show);
        $this->assign('levelList', $levelList);
        return $this->fetch('levelList');
    }

    /**
     * 添加修改编辑  性格特点
     */
    public function addEditLevel()
    {
        $id = I('id');
        if (IS_POST) {
            $data = I('post.');
            //            $characterValidate = Loader::validate('Character');
            //            if(!$characterValidate->batch()->check($data)){
            //                $return = ['status'=>0,'msg'=>'操作失败','result'=>$characterValidate->getError()];
            //                $this->ajaxReturn($return);
            //            }
            if ($id) {
                Db::name("married_user_level")->update($data);
            } else {
                Db::name("married_user_level")->insert($data);
            }
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'result' => '']);
        }
        $cat_list = M('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
        $this->assign('cat_list', $cat_list);
        $level = M("user_level")->find($id);
        $this->assign('level', $level);
        return $this->fetch('_level');
    }

    /**
     * 删除级别
     */
    public function delLevel()
    {
        $ids = I('post.ids', '');
        empty($ids) && $this->ajaxReturn(['status' => -1, 'msg' => '非法操作！']);
        $level_ids = rtrim($ids, ",");
        $res = Db::name('married_user_level')->whereIn('id', $level_ids)->delete();
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'url' => U("Admin/married/customer_index")]);
        }
        $this->ajaxReturn(['status' => -1, 'msg' => '操作失败', 'data' => '']);
    }

    /**
     *  订单列表
     * @return mixed
     */
    public function order_index()
    {
        return $this->fetch();
    }

    /**
     *  订单状态列表
     * @return mixed
     */
    public function order_state_index()
    {
        return $this->fetch();
    }

    /**
     * 订单状态列表数据
     * @return mixed
     */
    public function ajaxstateorder()
    {
        // 搜索条件
        $condition = array();
        I('email') ? $condition['email'] = I('email') : false;


        $model = M('married_counselor_order');
        $count = $model->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        //  搜索条件下 分页赋值
        foreach ($condition as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }

        I('mobile') ? $condition['b.woman_phone'] = I('mobile') : false;
        $orderStateList = $model->alias('a')->where($condition)->
                            join('married_order b','a.order_id=b.id','LEFT')->
                            order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->
                            field('a.create_time,a.id,a.user_id as counselor_id,a.order_id,a.step,b.man_name,b.woman_name,b.man_phone,b.woman_phone,b.married_date,b.married_money,b.order,b.user_id as kehu_user_id,b.combo')->
                            select();



        $comboList = Db::name('married_combo')->getField('id,title', true);
        $show = $Page->show();
        $this->assign('orderStateList', $orderStateList);
        $this->assign('comboList', $comboList);
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('pager', $Page);
        return $this->fetch();
    }

    public function ajaxorder()
    {
        // 搜索条件
        $condition = array();
        I('mobile') ? $condition['woman_phone'] = I('mobile') : false;
        I('email') ? $condition['email'] = I('email') : false;

        $au = I('autoF');
        if($au == '0'){
            $condition['counselor_id'] = 0;
        }

        $sort_order = I('order_by') . ' ' . I('sort');

        $model = M('married_order');
        $count = $model->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        //  搜索条件下 分页赋值
        foreach ($condition as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }


        $userList = $model->where($condition)->order($sort_order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $comboList = Db::name('married_combo')->getField('id,title', true);
        $show = $Page->show();
        $this->assign('userList', $userList);
        $this->assign('comboList', $comboList);
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('pager', $Page);
        return $this->fetch();
    }

    /**
     * 订单详情
     * @return mixed
     */
    public function married_order()
    {

        if (IS_GET) {
            $order_info = D('MarriedOrder')->where('id=' . I('GET.id', 0))->find();
            $this->assign('order_info', $order_info);

            $moboList = Db::name('married_combo')->select();

            $userList = M('users')->where(['is_counselor' => 1])->field('user_id,nickname')->select();


            $this->assign('userList', $userList);


            $characterList = M('user_character')->field('id,title')->select();


            $usrCatList = M('married_user_category')->field('cat_id,cat_name,user_list')->select();

            $this->assign('characterList', $characterList);

            $this->assign('usrCatList', $usrCatList);

            $this->assign('moboList', $moboList);

            return $this->fetch('_married_order');
            exit;
        }

        $GoodsCategory = D('MarriedOrder'); //

        $type = I('id') > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if (I('is_ajax') == 1) {
            // 数据验证
            $validate = \think\Loader::validate('MarriedOrder');
            if (!$validate->batch()->check(input('post.'))) {
                $error = $validate->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn($return_arr);
            } else {
                $GoodsCategory->data(input('post.'), true); // 收集数据
                //                $GoodsCategory->parent_id = I('parent_id');


                if ($type == 2) {
                    $GoodsCategory->isUpdate(true)->save(); // 写入数据到数据库
                } else {
//                    $GoodsCategory->order = 'MA' . time();
                    $GoodsCategory->save(); // 写入数据到数据库
                    $insert_id = $GoodsCategory->getLastInsID();
                }
                $return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Married/order_index')),
                );
                $this->ajaxReturn($return_arr);

            }
        }

    }


    // 套餐列表
    public function combo_index()
    {
        $where = "";
        $keyword = I('keyword');
        $where = $keyword ? " name like '%$keyword%' " : "";
        $count = Db::name("married_combo")->where($where)->count();
        $Page = $pager = new Page($count, 10);
        $levelList = Db::name("married_combo")->where($where)->order("sort")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $this->assign('pager', $pager);
        $this->assign('show', $show);
        $this->assign('levelList', $levelList);
        return $this->fetch('combo_index');
    }

    public function addEditCombo()
    {
        $id = I('id');
        if (IS_POST) {
            $data = I('post.');
            //            $characterValidate = Loader::validate('Character');
            //            if(!$characterValidate->batch()->check($data)){
            //                $return = ['status'=>0,'msg'=>'操作失败','result'=>$characterValidate->getError()];
            //                $this->ajaxReturn($return);
            //            }
            if ($id) {
                Db::name("married_combo")->update($data);
            } else {
                Db::name("married_combo")->insert($data);
            }
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'result' => '']);
        }
        $level = M("married_combo")->find($id);
        $this->assign('level', $level);
        return $this->fetch('_combo');
    }

    /**
     * 删除套餐
     */
    public function delcombo()
    {
        $ids = I('post.ids', '');
        empty($ids) && $this->ajaxReturn(['status' => -1, 'msg' => '非法操作！']);
        $level_ids = rtrim($ids, ",");
        $res = Db::name('married_combo')->whereIn('id', $level_ids)->delete();
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'url' => U("Admin/married/combo_index")]);
        }
        $this->ajaxReturn(['status' => -1, 'msg' => '操作失败', 'data' => '']);
    }

    // 联系我们列表
    public function contact_us()
    {
        $where = "";
        $keyword = I('keyword');
        $where = $keyword ? " name like '%$keyword%' " : "";
        $count = Db::name("married_user_contact_us")->where($where)->count();
        $Page = $pager = new Page($count, 10);
        $levelList = Db::name("married_user_contact_us")->where($where)->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $this->assign('pager', $pager);
        $this->assign('show', $show);
        $this->assign('levelList', $levelList);
        return $this->fetch();
    }

    /**
     * 分单流程
     * @return mixed
     */
    public function allotOrder($type='on',$order_id=0)
    {


        $result_user = [];

        $order_id = $order_id == 0 ?  I('GET.id', 0):$order_id;
        $this->assign('order_id', $order_id);

        $this->assign('all_user_list', Db::name('users')->where(['is_counselor'=>1])->field('user_id,nickname')->select());


        $order_info = D('MarriedOrder')->where('id=' . $order_id)->find();

        //查询是否设置了分组
        if($order_info['cat_id'] != 0){
            $catUsrList = Db::name('married_user_category')->where(['cat_id'=>$order_info['cat_id']])->getField('user_list');
            $map ="u.user_id IN (".implode(",",json_decode($catUsrList)).")";
        }
        $user_list = Db::name('users')
            ->alias('u')
            ->join('married_user_others b', 'b.user_id = u.user_id','left')
            ->join('married_user_level l', 'l.id = b.leveal_id','left')
            ->where('u.is_counselor',1)
            ->where($map)
            ->field('u.user_id,u.nickname,u.head_pic,b.leveal_id,b.master_character,b.bad_character,b.total_money,l.level,l.title as level_title')
            ->select();

        //3根据订单性格配置 人员
        $user_list_3 = [];
        foreach ($user_list as $value) {
            if(!empty($value['master_character'])){
                if (in_array($order_info['character_id'], json_decode($value['master_character']))) {
                    $user_list_3[] = $value;
                }
            }
        }
        //存在符合规则人员
        if (count($user_list_3) > 0) {
            if(count($user_list_3) == 1){
                $this->assign('user_list3', $user_list_3);
                $this->assign('result_user', $user_list_3);
                return $type == 'on' ? $this->fetch('allot_order') : array('user_list'=>$user_list_3,'order_id'=>$order_id);
            }
        }else{
            //不存在符合规则人员，给全部人员
            $user_list_3 = $user_list;
        }
        $this->assign('user_list3', $user_list_3);


        //4根据案例多少筛选人员
        $user_list_4 = [];
        $max = 0;
        foreach ($user_list_3 as $value) {
            $count = Db::name('married_order')->where(['combo' => $order_info['combo'], 'counselor_id' => $value['user_id']])->count();
            $value['count'] = $count;
            $user_list_4[$count][] = $value;
            if ($count > $max) {
                $max = $count;
            }
        }

        $user_list_4_1 = $user_list_4[$max];
        //存在符合规则人员
        if (count($user_list_4_1) > 0) {
            if(count($user_list_4_1) == 1){
                $this->assign('user_list4', $user_list_4_1);
                $this->assign('result_user', $user_list_4_1);
                return $type == 'on' ? $this->fetch('allot_order') : array('user_list'=>$user_list_4_1,'order_id'=>$order_id);
            }
        }else{
            //不存在符合规则人员，给全部人员
            $user_list_4_1 = $user_list_4;
        }
        $this->assign('user_list4', $user_list_4_1);


        //5根据二消多少 筛选
        $user_list_5 = [];
        $max_money = 0;
        foreach ($user_list_4_1 as $value) {
            $user_list_5[$value['total_money']][] = $value;
            if ($value['total_money'] > $max_money) {
                $max_money = $value['total_money'];
            }
        }

        $user_list_5_1 = $user_list_5[$max_money];
        //存在符合规则人员
        if (count($user_list_5_1) > 0) {
            if(count($user_list_5_1) == 1){
                $this->assign('user_list5', $user_list_5_1);
                $this->assign('result_user', $user_list_5_1);
                return $type == 'on' ? $this->fetch('allot_order') : array('user_list'=>$user_list_5_1,'order_id'=>$order_id);
            }
        }else{
            //不存在符合规则人员，给全部人员
            $user_list_5_1 = $user_list_5;
        }
        $this->assign('user_list5', $user_list_5_1);

        //6根据获取奖励单资格
        $user_list_6 = [];
        $award_max = 0;
        foreach ($user_list_5_1 as $key=>$value) {
            $count = Db::name('married_order_award')->where(['type' => 'good', 'user_id' => $value['user_id']])->sum('num');
            $value['sum'] = $count;
            $user_list_5_1[$key] = $value;
            $user_list_6[$count][] = $value;
            if ($count > $award_max) {
                $award_max = $count;
            }
        }
        $user_list_6_1 = $user_list_6[$award_max];

        //存在符合规则人员
        if (count($user_list_6_1) > 0) {
            if(count($user_list_6_1) == 1){
                $this->assign('user_list6', $user_list_6_1);
                $this->assign('result_user', $user_list_6_1);
                return $type == 'on' ? $this->fetch('allot_order') : array('user_list'=>$user_list_6_1,'order_id'=>$order_id);
            }
        }else{
            //不存在符合规则人员，给全部人员
            $user_list_6_1 = $user_list_5_1;
        }
        $this->assign('user_list6', $user_list_6_1);

        //7根据策划师等级
        $user_list_7 = [];
        $level_max = 1;
        foreach ($user_list_6_1 as $value) {
            $user_list_7[$value['level']][] = $value;
            if ($value['level'] < $level_max) {
                $level_max = $value['level'];
            }
        }

        $user_list_7_1 = $user_list_7[$level_max];

        //存在符合规则人员
        if (count($user_list_7_1) > 0) {
            if(count($user_list_7_1) == 1){
                $this->assign('user_list7', $user_list_7_1);
                $this->assign('result_user', $user_list_7_1);
                return $type == 'on' ? $this->fetch('allot_order') : array('user_list'=>$user_list_7_1,'order_id'=>$order_id);
            }else{
                $this->assign('result_user', $user_list_7_1);
            }
        }else{
            //不存在符合规则人员，给全部人员
            $user_list_7_1 = $user_list_6_1;
            $this->assign('result_user', $user_list_7_1);
        }

        $this->assign('user_list7', $user_list_7_1);
        return $type == 'on' ? $this->fetch('allot_order') : array('user_list'=>$user_list_7_1,'order_id'=>$order_id);
    }

    /**
     * 系统自动分单
     */
    public function autoAllotOrder(){
       $result = $this->allotOrder('off');

        $return = $this->addCounselorOrder($result['user_list'][0]['user_id'],$result['order_id']);
        if($return == true) {
            $ret = Db::name('married_order')->where(['id' => $result['order_id']])->setField('counselor_id', $result['user_list'][0]['user_id']);
            if ($ret) {
                $this->ajaxReturn(['status' => 1, 'msg' => '分配成功', 'userInfo' => $result]);
            }
            $this->ajaxReturn(['status' => -1, 'msg' => '自动分配失败，请手动分配', 'data' => '']);
        }else{
            $this->ajaxReturn(['status' => -1, 'msg' => '订单已经分配完毕，不能重复分配', 'data' => '']);
        }
    }
    /**
     * 系统批量自动分单
     */
    public function autoAllOrder(){

        $ids = I('ids');
        $idsList = explode(',',$ids);
        $success = 0;
        $faild = 0;
        foreach ($idsList as $value){
            if($value != ''){
                $result = $this->allotOrder('off',$value);

                $return = $this->addCounselorOrder($result['user_list'][0]['user_id'],$result['order_id']);
                if($return == true){
                    $ret = Db::name('married_order')->where(['id' => $result['order_id']])->setField('counselor_id', $result['user_list'][0]['user_id']);
                    if($ret!=false){
                        $success++;
                    }else{
                        $faild++;
                    }
                }

            }
        }

        $this->ajaxReturn(['status' => 1, 'msg' => '分配完毕', 'result'=>array('success'=>$success,'faild'=>$faild)]);
    }


    /**
     * 设置订单分配人员
     */
    public function setOrderUser()
    {
        $order_id = I('order_id');
        $user_id = I('user_id');
        $other_user_id = I('other_user_id');
        if(!empty($other_user_id)){
            $user_id = $other_user_id;
        }

        $return = $this->addCounselorOrder($user_id,$order_id);
        if($return == true){
            $ret = Db::name('married_order')->where(['id' => $order_id])->setField('counselor_id', $user_id);
            if ($ret) {
                $this->ajaxReturn(['status' => 1, 'msg' => '分配成功', 'url' => U("Admin/married/combo_index")]);
            }
            $this->ajaxReturn(['status' => -1, 'msg' => '操作失败', 'data' => '']);
        }else{
            $this->ajaxReturn(['status' => -1, 'msg' => '订单已经分配完毕，不能重复分配', 'data' => '']);
        }
    }

    /**
     * 顾问订单关联表增加一个数据
     */
    private function addCounselorOrder($user_id,$order_id){
        $data['user_id'] = $user_id;
        $data['order_id'] = $order_id;

        $retx = Db::name('married_counselor_order')->where('order_id',$order_id)->getField('user_id');

        if($retx!=false){
            return false;
        }

        $ret = Db::name('married_counselor_order')->add($data);
        if($ret){
            return true;
        }else{
            return false;
        }
    }

    //----温馨提示
    // 套餐列表
    public function warm_index()
    {
        $where = "";
        $keyword = I('keyword');
        $where = $keyword ? " name like '%$keyword%' " : "";
        $count = Db::name("warm_prompt")->where($where)->count();
        $Page = $pager = new Page($count, 10);
        $levelList = Db::name("warm_prompt")->where($where)->order("id")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $this->assign('pager', $pager);
        $this->assign('show', $show);
        $this->assign('levelList', $levelList);
        $this->assign('stetData', married_step());
        return $this->fetch('warm_index');
    }

    public function addEditWarm()
    {
        $id = I('id');
        if (IS_POST) {
            $data = I('post.');
            //            $characterValidate = Loader::validate('Character');
            //            if(!$characterValidate->batch()->check($data)){
            //                $return = ['status'=>0,'msg'=>'操作失败','result'=>$characterValidate->getError()];
            //                $this->ajaxReturn($return);
            //            }
            if ($id) {
                Db::name("warm_prompt")->update($data);
            } else {
                Db::name("warm_prompt")->insert($data);
            }
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'result' => '']);
        }
        $level = M("warm_prompt")->find($id);
        $this->assign('level', $level);
        $this->assign('stetData', married_step());
        return $this->fetch('_warm');
    }

    /**
     * 删除套餐
     */
    public function delwarm()
    {
        $ids = I('post.ids', '');
        empty($ids) && $this->ajaxReturn(['status' => -1, 'msg' => '非法操作！']);
        $level_ids = rtrim($ids, ",");
        $res = Db::name('married_combo')->whereIn('id', $level_ids)->delete();
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'url' => U("Admin/married/combo_index")]);
        }
        $this->ajaxReturn(['status' => -1, 'msg' => '操作失败', 'data' => '']);
    }


}